﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kakaroto.Models;
using Kakaroto.Pedidos;
using System.Data;
using System.Data.SqlClient;

namespace Kakaroto.Caixa
{
    public class CaixaActions
    {
        public void PreparaCheckout(string id)
        {
            KakarotoEntities _db = new KakarotoEntities();
            var pedido = (from p in _db.Pedido where p.Id == id select p).FirstOrDefault();
            var itensPedido = (from ip in _db.ItemPedido where ip.Id_Ped == id select ip);

            HttpContext.Current.Session["Cx_Pedido"] = pedido;
            HttpContext.Current.Session["Cx_ItensPedido"] = itensPedido.ToList();
            
            HttpContext.Current.Session["Quantia"] = 0.0;
            HttpContext.Current.Session["Troco"] = "Quantia não informada...";
        }

        public void EncerraCheckout()
        {
            string connectionString = "Data Source=tcp:kakaroto-server.database.windows.net,1433;Initial Catalog=kakaroto-db;Integrated Security=False;User ID=kakarotoadmin@kakaroto-server;Password=0iEuSouOGoku#;MultipleActiveResultSets=True;Connect Timeout=30;Encrypt=True;Application Name=EntityFramework";
            using (SqlConnection connection = new SqlConnection(connectionString))
                using (SqlCommand command = connection.CreateCommand())
                {
                    Pedido pedido = HttpContext.Current.Session["Cx_Pedido"] as Pedido;
                    command.CommandText = "UPDATE Pedido "
                                        + "SET Pedido.Desconto = @desconto, Pedido.Servico = @servico, Pedido.Saida = @saida, "
                                        + "Pedido.Status_Pagamento = @status, Pedido.Tipo_Pagamento = @tipo, Pedido.Total = @total "
                                        + "WHERE Pedido.Id = @id";
                
                    command.Parameters.AddWithValue("@desconto", pedido.Desconto);
                    command.Parameters.AddWithValue("@servico", pedido.Servico);
                    command.Parameters.AddWithValue("@saida", pedido.Saida);
                    command.Parameters.AddWithValue("@status", pedido.Status_Pagamento);
                    command.Parameters.AddWithValue("@tipo", pedido.Tipo_Pagamento);
                    command.Parameters.AddWithValue("@total", pedido.Total);
                    command.Parameters.AddWithValue("@id", pedido.Id);

                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                }
        }

        public void SetAllNull()
        {
            HttpContext.Current.Session["Cx_Pedido"] = null;
            HttpContext.Current.Session["Cx_ItensPedido"] = null;
            HttpContext.Current.Session["Quantia"] = null;
            HttpContext.Current.Session["Troco"] = null;
        }
    }
}